<?php

namespace app\admin\service;

use app\admin\model\Page as PageModel;

class PageService
{
    protected $model;

    public function __construct(){
        $this->model = app()->make(PageModel::class);
    }

    /**
     * @param $where
     * @param $pageSize
     * @return PageModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryListByPage($where, $pageSize = 15)
    {
        $list = $this->model->where($where)->field('id, title, route, created_time')->order('created_time desc')->paginate($pageSize);
        return $list;
    }

    /**
     * @param int $id
     * @return PageModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryDetail(int $id){
        $article = $this->model->where('id', $id)->find();
        $article['content'] = str_replace("'","\"", $article['content']);
        return $article;
    }
    public function save(array $data): int
    {
        //print_r($data);
        $result = null;
        if (empty($data['id'])) {
            $this->model->insert($data);
            return $this->model->getLastInsID();
        } else {
            $this->model->where('id', $data['id'])->save($data);
            return $data['id'];
        }
    }

    public function delete(int $id): bool
    {
        return $this->model->where('id', $id)->delete();
    }

    /**
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function queryCount(): int{
        return $this->model->count();
    }
}